package org.security.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author jt
 * @date 2024/7/22 21:38
 */
public class RequestUtil {

    public static JSONObject getBody(HttpServletRequest request) {
        // 使用StringBuilder来构建请求体的字符串
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        catch (IOException e){
            throw new RuntimeException("检查body");
        }
        // 将StringBuilder转换为String
        String jsonBody = stringBuilder.toString();

        // 使用JSONObject解析JSON字符串
        JSONObject jsonObject = JSONObject.parseObject(jsonBody);
        return jsonObject;

    }

    public static String bodyToStr(HttpServletRequest request){
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        catch (IOException e){
            throw new RuntimeException("检查body");
        }
        // 将StringBuilder转换为String
        String jsonBody = stringBuilder.toString();
        return jsonBody;
    }
}
